package cn.gov.msa.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import cn.gov.msa.dao.MaritimeOrgMapper;
import cn.gov.msa.model.MaritimeOrg;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

//import com.msa.msaportal.entity.UserComponent;

public class WebServiceTools {//这个类应该可以直接用
	
	/**
	 * 根据url得到返回数据
	 * 固定访问名称为
	 * @param url
	 * @return
	 * @throws DocumentException 
	 * @throws XmlPullParserException 
	 * @throws IOException 
	 */
	public static String getDataByUrl(String url,String methods,String parameter) throws DocumentException, IOException, XmlPullParserException {
		
		if(urlIsReach(url) == false){
			return "{\"result\":\"0\",\"info\":\"此链接地址不可用。URL：" + url + "\"}";
		}
		
		String nameSpace = "";
		String result = "";
		
		nameSpace = gettargetNamespace(url);
		result = getRemoteInfo(nameSpace, url, methods, parameter);

		return result;
	}
	
	/**
	 * 根据多个参数获取返回数据
	 * @param url
	 * @param methods
	 * @param parameter
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	public static String getDatasByUrl(String url,String methods,String[] parameter) throws DocumentException, IOException, XmlPullParserException {
		
		if(urlIsReach(url) == false){
			return "{\"result\":\"0\",\"info\":\"此链接不可用。URL：" + url + "\"}";
		}
		
		String nameSpace = "";
		String result = "";

		nameSpace = gettargetNamespace(url);
		result = getRemoteInfo(nameSpace, url, methods, parameter);

		return result;
	}
	
	/**
	 * 根据wsdl地址得到命名空间
	 * @param url
	 * @return
	 * @throws DocumentException
	 */
	public static String gettargetNamespace(String url) throws DocumentException{
		 SAXReader reader = new SAXReader();
		 Document   document = reader.read(url); 
		 Element root = document.getRootElement(); 
		return  root.attributeValue("targetNamespace");
	}
	/**
	 * 根据多个参数获取命名空间
	 * @param targetNamespace
	 * @param url
	 * @param methods
	 * @param parameter
	 * @return
	 * @throws IOException
	 * @throws XmlPullParserException
	 */
	public static String getRemoteInfo(String targetNamespace,String url,String methods,String[] parameter) throws IOException, XmlPullParserException {
		String urls=url.replace("?wsdl", "");
		// 命名空间
		String nameSpace = targetNamespace;
		// 调用的方法名称
		String methodName = methods;
		// EndPoint
		String endPoint = url;
		// SOAP Action
		String soapAction = targetNamespace+urls;
		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace, methodName);
		for (int i = 0; i < parameter.length; i++) {
			rpc.addProperty(
					"arg"+i,
					parameter[i]);
		}
		
		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.bodyOut = rpc;
		// 设置是否调用的是dotNet开发的WebService
		envelope.dotNet = false;
		// 等价于envelope.bodyOut = rpc;
		envelope.setOutputSoapObject(rpc);

		HttpTransportSE transport = new HttpTransportSE(endPoint, 10*1000);
		
			// 调用WebService
			transport.call(soapAction, envelope);
	

		// 获取返回的数据
		SoapObject object = (SoapObject) envelope.bodyIn;
		// 获取返回的结果
		String result = object.getProperty(0).toString();
		//System.out.println(result);
		return result;
		// 将WebService返回的结果显示在TextView中
	}
	
	public static String getRemoteInfo(String targetNamespace,String url,String methods,String parameter) throws IOException, XmlPullParserException {
		String urls=url.replace("?wsdl", "");
		// 命名空间
		String nameSpace = targetNamespace;
		// 调用的方法名称
		String methodName = methods;
		// EndPoint
		String endPoint = url;
		// SOAP Action
		String soapAction = targetNamespace+urls;
		// 指定WebService的命名空间和调用的方法名
//		System.out.println(nameSpace + "  " +methodName  + "  " + endPoint +"  "+parameter);
		SoapObject rpc = new SoapObject(nameSpace, methodName);
		rpc.addProperty(
				"arg0",
				parameter);
		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.bodyOut = rpc;
		// 设置是否调用的是dotNet开发的WebService
		envelope.dotNet = false;
		// 等价于envelope.bodyOut = rpc;
		envelope.setOutputSoapObject(rpc);

		HttpTransportSE transport = new HttpTransportSE(endPoint, 10*1000);

		
			// 调用WebService
			
			transport.call(soapAction, envelope);
			
	

			SoapObject object = (SoapObject) envelope.bodyIn;
			// 获取返回的结果
			String result = object.getProperty(0).toString();
			//System.out.println(result);
			return result;
			// 将WebService返回的结果显示在TextView中
	}
	
	public static void dayin(String orgCode,short level,	MaritimeOrgMapper maritimeOrgMapper) throws DocumentException, IOException, XmlPullParserException, InterruptedException {
		String wsdl="http://198.10.10.159:8011/CommissionInvoke/proxy/LDAPService_BJproxy?wsdl";
		String method = "OrgQueryServices_queryOrg4Detail";
		String param = "{'orgCode':'"+orgCode+"','isQuerySubOrg':'1'}";
		JSONObject returnMsg = JSONObject.fromObject(WebServiceTools.getDataByUrl(wsdl, method, param));
		if("1".equals(returnMsg.optString("result"))) {
			System.out.println(returnMsg.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getString("orgCode")+returnMsg.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getString("orgName")+level);			
			JSONObject org=returnMsg.getJSONObject("datas").getJSONObject("table").getJSONObject("row");
			MaritimeOrg maritimeOrg=new MaritimeOrg();
			maritimeOrg.setOrgcode4a(org.getString("orgCode"));
			maritimeOrg.setOrgcode(org.getString("orgCode"));
			maritimeOrg.setPorgcode(org.optString("parentOrgId"));
			maritimeOrg.setOrglevel(level);
			maritimeOrg.setOrgtype(org.optString("orgType"));
			maritimeOrg.setOrgname(org.getString("orgName"));
			maritimeOrg.setOrgfullname(org.getString("orgName"));
			maritimeOrg.setProvincecode(org.optString("province"));
			maritimeOrg.setCitycode(org.optString("city"));
			maritimeOrg.setAddress(org.optString("address"));
			maritimeOrg.setPostalcode(org.optString("postalCode"));
			maritimeOrg.setWebsite(org.optString("website"));
			maritimeOrg.setTelephone(org.optString("telephoneNumber"));
			maritimeOrg.setFaxnumber(org.optString("rescueFax"));
			maritimeOrgMapper.insertSelective(maritimeOrg);
			JSONArray jArray = returnMsg.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getJSONArray("table");
			for (int i=0; i< jArray.size(); i++) {
				JSONObject table = JSONObject.fromObject(jArray.get(i));
				String  tableName= (String)table.get("tableName");
				if("subOrg".equals(tableName)){
					JSONArray subOrgArray = table.getJSONArray("row");
					if(!subOrgArray.isEmpty()) {
						for (Object object : subOrgArray) {
							JSONObject fromObject = JSONObject.fromObject(object);
							String orgCode1 = (String)fromObject.get("orgCode");
							WebServiceTools.dayin(orgCode1, (short) (level+1),maritimeOrgMapper);
						}	
					}			
				}
			}	
		}else {
			System.out.println(orgCode+"查找失败");
		}
	}
	
	/**
	 * 判断URL是否可用
	 * @param url 待判断的URL
	 * @return true: 可达 false: 不可达
	 */
	public static boolean urlIsReach(String url) {
		if (url==null) {
			return false;
		}
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setConnectTimeout(3 * 1000); // 3秒内无法链接判断为连接不可用
			if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	public static void main(String[] args) throws DocumentException, IOException, XmlPullParserException, InterruptedException {

		String wsdl="http://198.10.10.159:8011/CommissionInvoke/proxy/LDAPService_BJproxy?wsdl";
		String method = "UserQueryServices_userQuery4Detail";
		String param = "{'userId':'320323198508230010','isQueryRoles':'1'}";
		JSONObject returnMsg = JSONObject.fromObject(WebServiceTools.getDataByUrl(wsdl, method, param));
		System.out.println(returnMsg);
		
		
//		WebServiceTools.dayin("00", 1);
		
		
//		String wsdl="http://10.10.0.233:8080/MSAPortal/ws/TemplateOrStyle?wsdl";
//		String method = "addTemplateOrStyle";
//		String param = "{'templateOrStyleName':'1ss3','orgName':'13','orgId':'13','description':'13','public':'1','author':'13','authorId':'13','alter':'13','alterId':'13','createTime':'13','updateTime':'31','files':'df','fileName':'jfali.css','fileType':'jsp','templateOrStyleId':'13'}";
//	    String returnMsg = getDataByUrl(wsdl, method, param);
//	    System.out.println(returnMsg);
		
		/*String wsdl="http://172.16.16.200:7001/LdapDatas/LDAPDataService?wsdl";
		String method = "UserQueryServices_userQueryByCondition";
		String param = "{'orgCode':'00','pageSize':'1000'}";
	    String returnMsg = getDataByUrl(wsdl, method, param);
	    System.out.println(returnMsg);*/
		
	   /* String wsdl="http://172.16.16.199:9001/OneService/gtasksWebservice?wsdl";
		String method = "gTasksFind";
		String param = "{'userId':'211223199007010000','accessPlatform':'','isDone':'1'}";
	    String returnMsg = getDataByUrl(wsdl, method, "");
	    System.out.println(returnMsg);*/
		 
	/*	String wsdl="http://localhost:7001/GtaskService/gtasksWebservice?wsdl";   //这个服务不知道为啥172.16.16.199:9001上的不行
		String method ="gTasksUpdateOrAdd";  //appTaskId即该代办在原来系统中的ID，如果appTaskId userId appName在代办库已经有，则进行更新操作
		String param = "{'userId':'120103197502204518','appTaskId':'ABCDEG','appId':'001','appName':'4A系统','taskName':'测试用3','taskURL':'http://cmp.msa.gov.cn:7001/CMPService/admin/bpm/userImpower/officer.jsp','isDone':'1','businessType':'系统管理','statusName':'已处理'}";
	    String returnMsg = getDataByUrl(wsdl, method, param);
	    System.out.println(returnMsg);*/
		
		/*String wsdl="http://127.0.0.1:7001/GtaskService/busiDealDataWebservice?wsdl";
		String method ="busiDealDataFind";  //appTaskId即该代办在原来系统中的ID，如果appTaskId userId appName在代办库已经有，则进行更新操作
		String param = "{'userId':'FZTEST000000000001','accessPlatform':''}";
	    String returnMsg = getDataByUrl(wsdl, method, param);
	    System.out.println(returnMsg);
	    */
		
//			String wsdl="http://127.0.0.1:7001/GtaskService/busiDealDataWebservice?wsdl";
//		    String method = "busiDealDataAdd";
//		    String param = "{'userId':'FZTEST000000000001','appId':'011','appName':'公司管理系统','typeName':'系统','busiName':'公司管理1','busiURL':'http://www.baidu.com','businessType':'公司管理'}";
//		    String returnMsg = getDataByUrl(wsdl, method, param);
//		    System.out.println(returnMsg);
		

			/*String wsdl="http://172.16.16.200:7001/LdapDatas/LDAPDataService?wsdl";
		    String method = "UserQueryServices_userQuery4Detail";
		    String param = "{'userId':'120103197502204518','isQueryRoles':'1','isQueryorgs':'1','isQueryDepts':'1','pageSize':'10','currentPage':'1'}";
		    String returnMsg = getDataByUrl(wsdl, method, param);
		    System.out.println(returnMsg);*/
	    
	    
		/*String wsdl="http://172.16.16.200:7001/LdapDatas/LDAPDataService?wsdl";
	    String method = "UserQueryServices_userQueryByCondition";
	    String param = "{'orgCode':'00','pageSize':'10','currentPage':'1'}";
	    String returnMsg = getDataByUrl(wsdl, method, param);
	    System.out.println(returnMsg);*/
		
		/*String wsdl="http://172.16.16.200:7001/LdapDatas/LDAPDataService?wsdl";
	    String method = "RoleQueryServices_roleQueryUsersList";
	    String param = "{'roleCode':'CMP_001_R00011','pageSize':'20','currentPage':'1','maritimeOrgCode':'00'}";
	    String returnMsg = getDataByUrl(wsdl, method, param);
	    System.out.println(returnMsg);*/
		
		/*String wsdl="http://172.16.16.200:7001/LdapDatas/LDAPDataService?wsdl";
	    String method = "OrgQueryServices_queryOrg4Detail";
	    String param = "{'orgCode':'00','isQuerySubOrg':'1'}";
	    String returnMsg = getDataByUrl(wsdl, method, param);
	    System.out.println(returnMsg);*/
		
//		 String wsdl="http://localhost:7001/RMS/ComponentServices?wsdl";
//		 String method ="queryComponent";  //appTaskId即该代办在原来系统中的ID，如果appTaskId userId appName在代办库已经有，则进行更新操作
//		 String param = "{'componentType':'福建组件'}";
//		 String returnMsg = getDataByUrl(wsdl, method, param);
//		 System.out.println(returnMsg);
 		
		 
		
//			String url = "http://172.16.16.200:7001/LdapDatas/LDAPDataService?wsdl";
//			String methods = "UserQueryServices_userQueryByCondition";
//			String parameter = "{'orgCode':'00','pageSize':'3000','currentPage':'1'}";
//			String returnMsg = getDataByUrl(url, methods, parameter);
//			System.out.println(returnMsg);
			
			
//	    String wsdl="http://localhost:7001/RMS/UniversalComService?wsdl";
//		String method ="buttonDelete";  //appTaskId即该代办在原来系统中的ID，如果appTaskId userId appName在代办库已经有，则进行更新操作
//		String param = "{'buttonName':'Button2','componentId':'19'}";
//	    String returnMsg = getDataByUrl(wsdl, method, param);
	    //System.out.println(returnMsg);
		
//		String wsdl="http://localhost:7001/RMS/UniversalComService?wsdl";
//		String method ="buttonUpdateOrAdd";  //appTaskId即该代办在原来系统中的ID，如果appTaskId userId appName在代办库已经有，则进行更新操作
//		String param = "{'buttonName':'Button13','componentId':'20','URL':'http://baidu.com','typeName':'Type3'}";
//	    String returnMsg = getDataByUrl(wsdl, method, param);
//	    System.out.println(returnMsg);
	}
}
